<?php


namespace app\api\controller;


use app\admin\model\OnlineRecord;
use app\BaseController;

//引入模型
use app\common\service\TenImService;
use app\models\system\Banner;
use app\models\system\Prohibit;
use app\models\system\Rooms;
use app\models\user\UserGroup;
use app\models\system\Lecturer;
use app\models\system\Curriculum;
use app\models\system\Market;
use app\models\system\Records;
use app\models\system\Courseware;

use app\models\system\SystemWebsite;
use app\models\system\WebsiteDefailt;
use app\models\system\Warehouse;
use app\models\system\Interworking;


use app\Request;
use broadcast\services\UtilService as Util;
use broadcast\utils\Curl;
use broadcast\redis\setRedis;
use app\models\system\VideoCallError;
use EasyAdmin\upload\Uploadfile;

/**
 * Class Index
 * @package app\api\controller
 */
class Index extends BaseController
{
    /**
     * 网站配置
     * website  网站名称
     */
    public function website ()
    {

        $data = Util::getMore([
            ['website', ''],
            ['roomid', ""]
        ]);

        if ($data['website'] == '') return app("json")->fail("参数错误");
        $data['website'] = reversibleDecrypt($data['website']);

        $low_config = setRedis::getCache($data['website'], "info");

        if ($low_config) {
            $config = $low_config;
        } else {

            $config = SystemWebsite::where("website_ident", $data['website'])->find();
            if ($config) {
                $config = $config->toArray();
                setRedis::setCache($data['website'], 'info', $config, 0);
            }

        }

        if (!isset($config['state'])) $config['state'] = 1;
        if (!isset($config['curriculum_arrange_pattern'])) $config['curriculum_arrange_pattern'] = 1;
        if (!isset($config['lecturer_arrange_pattern'])) $config['lecturer_arrange_pattern'] = 1;
        if (!isset($config['lecturer_image'])) $config['lecturer_image'] = "";
        if (!isset($config['lecturer_image_moblie'])) $config['lecturer_image_moblie'] = "";
        if (!isset($config['curriculum_image'])) $config['curriculum_image'] = "";
        if (!isset($config['curriculum_image_moblie'])) $config['curriculum_image_moblie'] = "";
        if (!isset($config['browser_pattern_moblie'])) $config['browser_pattern_moblie'] = 0;



        if (!$config) return app("json")->fail("直播间不存在");
        if ($config['overdue'] < time()) return app("json")->fail("直播间已关闭");
        if ($config['state'] != 1) return app("json")->fail("直播间已关闭");

        unset($config['peak']);
        unset($config['website_ident']);
        unset($config['create_time']);
        unset($config['moblie_line']);
        unset($config['pc_line']);
        unset($config['spare_domain']);
        unset($config['primary_domain_name']);
        unset($config['mysql_host']);
        unset($config['mysql_usename']);
        unset($config['mysql_pass']);
        unset($config['admin_login_background']);
        unset($config['update_time']);
        unset($config['mysql_network']);
        unset($config['redis_network']);
        unset($config['tencent_username']);
        unset($config['tencent_password']);
        unset($config['open_platform_appid']);
        unset($config['open_platform_secrt']);
        unset($config['public_platform_appid']);
        unset($config['public_platform_secrt']);
    
        $list = $config;

        unset($list['id']);
        unset($list['website_state']);
        unset($list['overdue']);

        //获取网站的配置功能

        $low_configInfo = setRedis::getCache($data['website'], "default");

        if ($low_configInfo) {
            $configInfo = $low_configInfo;
        } else {

            $configInfo = WebsiteDefailt::where('website', $data['website'])->find();
            if ($configInfo) {
                $configInfo = $configInfo->toArray();
                setRedis::setCache($data['website'], "default", $configInfo, 0);
            }

        }

        if ($configInfo) {

            //配色方案
            $colours = allColor();
            $list['colours'] = $colours[$list['molding']];
            unset($list['colours']['title']);
            $list['config'] = json_decode($configInfo['configure'], true);
            if (!isset($list['config']['whether_envelopes'])) $list['config']['whether_envelopes'] = 0;
            if (!isset($list['config']['whether_luck_draw_function'])) $list['config']['whether_luck_draw_function'] = 0;
            if (!isset($list['config']['whether_gift_function'])) $list['config']['whether_gift_function'] = 0;
        } else {

            $list['config'] = [
                "whether_teacher" => "1",             //老师简介
                "whether_curriculum" => "1",          //课程安排
                "whether_economics" => "1",           //财经日历
                "whether_previous" => "1",            //往期视频
                "whether_dragon_tiger" => "1",        //龙虎榜单
                "whether_individual_stocks" => "1",   //个股诊断
                "whether_market_review" => "1",       //市场评论
                "whether_index_download" => "1",      //指标下载
                "whether_advanced_courseware" => "1", //高级课件
                "whether_warehouse_reminder" => "1",  //建仓提醒
                "whether_closing_reminder" => "1",    //平仓提醒
                "whether_industry_trends" => "1",     //行情动态
                "whether_lecturer_ranking" => "1",    //讲师排行
                "whether_sign" => "1",                //签到
                'whether_envelopes' => '0',           //红包
                'whether_luck_draw_function' => "0",  //抽奖功能
                'whether_gift_function' => '0'        //礼物功能
            ];

        }
        $list['web_token'] = lockcode($data['website'], 'ENCODE');

        //处理数据
        unset($list['molding']);


        //获取互通规则   end
        if ($config['website_state'] != 1 && $data['roomid'] != 888 && $data['roomid'] != 999) {
            $list['now_state'] = 201;
        } else {
            $list['now_state'] = 200;
        }

        return app("json")->success($list);
    }

    /**
     * 房间基本配置
     */
    public function index(Request $request)
    {
        $data = Util::postMore([
            ['roomid', ''],
            ['userID', '']
        ]);
        session('website', $request->website());
        $list = array();

        if ($data['roomid'] == '') return app("json")->fail("未选择房间号");
        //判断房间是否存在

        $data['ip'] = getIps();
        $Banlean = new Prohibit();
        //判断是否为被封禁用户或IP   start
        if ($data['ip'] != '') {
            $Banlean = $Banlean->where("ip", ip2long($data['ip']));
        }

        $Banlean = $Banlean->find();

        if ($Banlean) return app("json")->fail("用户名或IP受限！");
        $low_roomInfo = setRedis::getCache(session("website"), "roomInfo" . $data['roomid']);
        if ($low_roomInfo) {
            $roomInfo = $low_roomInfo;
        } else {

            $roomInfo = Rooms::where("roomid", $data['roomid'])->find();
            if ($roomInfo) {
                $roomInfo = $roomInfo->toArray();
                setRedis::setCache(session("website"), "roomInfo" . $data['roomid'], $roomInfo);
            }

        }


        if (empty($roomInfo)) return app("json")->fail("房间号不存在");
        if ($roomInfo['status'] != 1) return app("json")->fail("房间已关闭");

        // 处理用户是否中途更换房间记录 todo
        if ($data['userID']) {
            $this->checkLoginRoom($data['roomid'], $data['userID']);
        }


        unset($roomInfo['id']);
        unset($roomInfo['create_time']);

        //处理房间号
        $list['info'] = $roomInfo;

        //用户组
        $low_usergroup = setRedis::getCache(session("website"), 'userGroupList');

        if ($low_usergroup) {
            $usergroup = $low_usergroup;
        } else {
            $usergroup = UserGroup::order("sort desc")->select()->toArray();
            if ($usergroup) {
                setRedis::setCache(session("website"), 'userGroupList', $usergroup, 0);
            }
        }

        if ($usergroup) {
            foreach ($usergroup as &$value) {
                unset($value['ico']);
                unset($value['create_time']);
                unset($value['sort']);
            }
        }

        $list['group'] = $usergroup;

        $inter_works = [$data['roomid']];
        //获取互通规则   start
        if ($data['roomid'] != '999') {
            $low_Interworking = setRedis::getCache(session('website'), 'nowInterWork');
            if ($low_Interworking) {
                $Interworking = $low_Interworking;
            } else {
                $Interworking = Interworking::where('website', session('website'))->select()->toArray();
                setRedis::setCache(session('website'), 'nowInterWork', $Interworking, 0);
            }

            foreach ($Interworking as $item) {
                $roomds = explode(",", $item['roomds']);
                if (in_array((string)$data['roomid'], $roomds)) {
                    $inter_works = $roomds;
                }
            }
        } else {
            $inter_works = setRedis::getRoomsKeys(session("website"), "roomInfo");
        }


        $list['inter_works'] = $inter_works;


        return app("json")->success($list);

    }

    // 检测进房间状态
    private function checkLoginRoom($roomid, $userID)
    {
        // 获取用户信息
        $users = TenImService::getImAccount([$userID]);
        if (isset($users['UserProfileItem'][0]['ProfileItem'][0]['Value'])) {
            $nick = $users['UserProfileItem'][0]['ProfileItem'][0]['Value'];
        } else {
            return;
        }
        $website = spliceStr($nick, '_W_', '_R_');
        $rid = spliceStr($nick, '_R_', '_U_');
        $username = spliceStr($nick, '_U_', '_X_');
        if (!$website or !$rid or !$username) {
            return;
        }

        $loginRecordInsert = setRedis::getCache($website, "loginRecordInsert:" . $username);
        $userInfo = setRedis::getUserCache($website, 'usersList#*:' . $username);
        $userInfo = $userInfo['data'];

        if ($rid != $roomid && $loginRecordInsert && $userInfo) {
            // 修改在线数量，在线记录
            $loginRecordInsert = json_decode($loginRecordInsert, true);
            setRedis::delCache($website, "loginRecordInsert:{$username}");
            // 缓存分钟在线数量
            $this->cacheMinuteNum('decr', $website, $rid, $userInfo);
            try {
                $end_time = time();
                $duration = $end_time - $loginRecordInsert['start_time'];
                $updateData = [
                    'end_time' => time(),
                    'duration' => $duration
                ];
                OnlineRecord::where('id', $loginRecordInsert['id'])->update($updateData);
            } catch (\Exception $e) {
                return app("json")->fail($e->getMessage());
            }

            // 增加在线数量，在线记录
            $start_time = time();
            $insertData = [
                'rid' => $roomid,
                'username' => $username,
                'extension' => $userInfo['extension'] ?? '',
                'group' => $userInfo['group'] ?? '',
                'ip' => $userInfo['create_ip'] ?? '',
                'start_time' => $start_time,
                'home' => $userInfo['create_home']
            ];

            // 缓存分钟在线数量
            $this->cacheMinuteNum('incr', $website, $roomid, $userInfo);
            try {
                $insertId = OnlineRecord::insertGetId($insertData);
                if ($insertId) {
                    // 记录插入记录表的ID和进入时间
                    setRedis::setCache($website, "loginRecordInsert:{$username}", json_encode(['id' => $insertId, 'start_time' => $start_time]));
                }
            } catch (\Exception $e) {
                return app("json")->fail($e->getMessage());
            }

            $userImNewNick = TenImService::getAccount($roomid, $userInfo);
            if ($userImNewNick) {
                $userImNewNick = $userImNewNick['Nick'];
                // 修改IM昵称
                TenImService::setUserProfile([
                    'From_Account' => $userID,
                    'ProfileItem' => [
                        ['Tag' => 'Tag_Profile_IM_Nick', 'Value' => $userImNewNick]
                    ]
                ]);

            }

        }
    }

    // 缓存每分钟记录
    private function cacheMinuteNum($type, $website, $rid, $userInfo)
    {
        $now_date = date('Y-m-d');
        $up_minute = date('H:i', strtotime("-1 minutes"));
        $now_minute = date('H:i');


        // 当前今天房间key
        $nowDateRoomKey = "onlineData:{$now_date}:rid:{$rid}";

        // 获取前一分中房间下用户数据
        $upMinuteRoomData = setRedis::getRoomsData($website, $nowDateRoomKey, $up_minute);
        // 如果前一分钟房间有数据和当前分钟房间没有用户数据，则赋值前一分钟数据
        if ($upMinuteRoomData && !setRedis::getRoomsData($website, $nowDateRoomKey, $now_minute)) {
            setRedis::insertRoomsData($website, $nowDateRoomKey, $now_minute, $upMinuteRoomData);
        }
        if (substr($userInfo['username'], 0, 2) == 'yk') {
            $data = ['tourist_nums' => 1];
        } else {
            $data = ['users_nums' => 1];
            if ($userInfo['extension']) $data[$userInfo['extension']] = 1;
        }
        // 更改房间用户数量
        setRedis::changeRoomsData($type, $website, $nowDateRoomKey, $now_minute, $data);
    }


    /**
     * 功能信息
     * 固定功能
     */
    public function finance(Request $request)
    {
        $data = Util::postMore([
            ['roomid', '']
        ]);
        //获取网站的配置功能

        session("website", $request->website());

        $low_website_info = setRedis::getCache(session("website"), "info");
        if ($low_website_info) {
            $website_info = $low_website_info;
        } else {

            $website_info = SystemWebsite::where("website_ident", session("website"))->find();
            if ($website_info) {
                $website_info = $website_info->toArray();
                setRedis::setCache(session("website"), 'info', $website_info, 0);
            }
        }
        if (!isset($website_info['curriculum_arrange_pattern'])) $website_info['curriculum_arrange_pattern'] = 1;
        if (!isset($website_info['lecturer_arrange_pattern'])) $website_info['lecturer_arrange_pattern'] = 1;

        $low_configInfo = setRedis::getCache(session("website"), "default");
        if ($low_configInfo) {
            $configInfo = $low_configInfo;
        } else {
            $configInfo = WebsiteDefailt::where('website', session("website"))->find();
            if ($configInfo) {
                $configInfo = $configInfo->toArray();
                setRedis::setCache(session("website"), "default", $configInfo, 0);
            }
        }


        if ($configInfo) {
            $config = json_decode($configInfo['configure'], true);
        } else {
            $config = [
                "whether_teacher" => "1",             //老师简介
                "whether_curriculum" => "1",          //课程安排
                "whether_economics" => "1",           //财经日历
                "whether_previous" => "1",            //往期视频
                "whether_dragon_tiger" => "1",        //龙虎榜单
                "whether_individual_stocks" => "1",   //个股诊断
                "whether_market_review" => "1",       //市场评论
                "whether_index_download" => "1",      //指标下载
                "whether_advanced_courseware" => "1", //高级课件
                "whether_warehouse_reminder" => "1",  //建仓提醒
                "whether_closing_reminder" => "1",    //平仓提醒
                "whether_industry_trends" => "1",     //行情动态
                "whether_lecturer_ranking" => "1",    //讲师排行
                "whether_sign" => "1",                //签到

            ];
        }
        //处理数据
        $list = array();

        //讲师团队是否存在
        if ($config['whether_teacher'] == 1 && $website_info['lecturer_arrange_pattern'] == 1) {
            $low_Lecturer = setRedis::getCache(session('website'), "LecturerList");
            if ($low_Lecturer) {
                $lecturer = $low_Lecturer;
            } else {
                $lecturer = Lecturer::where("state", 1)->order("rank desc")->select();
                if ($lecturer) $lecturer = $lecturer->toArray();
                setRedis::setCache(session('website'), "LecturerList", $lecturer, 0);
            }

            foreach ($lecturer as &$item) {
                $item['content'] = tohtml($item['content']);
                unset($item['website']);
                unset($item['create_time']);
                unset($item['state']);
                unset($item['rank']);
            }


            $list['lecturer'] = $lecturer;
        }


        //轮播广告是否存在

        $config['rotation'] = 1;
        if ($config['rotation'] == 1) {
            $low_banner = setRedis::getCache(session("website"), 'bannList');
            if ($low_banner) {
                $banner = $low_banner;
            } else {
                $banner = Banner::select();
                if ($banner) {
                    $banner = $banner->toArray();
                    setRedis::setCache(session("website"), 'bannList', $banner, 0);
                }
            }
            $bannerList = array();
            if ($banner) {
                foreach ($banner as &$value) {
                    unset($value['id']);
                    unset($value['create_time']);
                    $bannerList[] = $value;
                }
            }
            $list['bannerList'] = $bannerList;
        }
        //判断课程安排是否存在
        if ($config['whether_curriculum'] == 1 && $website_info['curriculum_arrange_pattern'] == 1) {
            $weekList = array();

            $low_week = setRedis::getCache(session("website"), "CurriculumList");
            if ($low_week) {
                $week = $low_week;
            } else {
                $week = Curriculum::order("start_time asc")->select();
                if ($week) {
                    $week = $week->toArray();
                    setRedis::setCache(session("website"), "CurriculumList", $week, 0);
                }
            }

            //处理数据
            foreach ($week as &$item) {
                $item['section'] = $item['start_time'] . '-' . $item['end_time'];
                $item['monday'] = json_decode($item['monday'], true);
                $item['tuesday'] = json_decode($item['tuesday'], true);
                $item['wednesday'] = json_decode($item['wednesday'], true);
                $item['thursday'] = json_decode($item['thursday'], true);
                $item['friday'] = json_decode($item['friday'], true);
                $item['saturday'] = json_decode($item['saturday'], true);
                $item['sunday'] = json_decode($item['sunday'], true);

                if ($item['monday']['name'] == '') $item['monday']['content'] = '';
                if ($item['tuesday']['name'] == '') $item['tuesday']['content'] = '';
                if ($item['wednesday']['name'] == '') $item['wednesday']['content'] = '';
                if ($item['thursday']['name'] == '') $item['thursday']['content'] = '';
                if ($item['friday']['name'] == '') $item['friday']['content'] = '';
                if ($item['saturday']['name'] == '') $item['saturday']['content'] = '';
                if ($item['sunday']['name'] == '') $item['sunday']['content'] = '';

            }


            $weekList = array();
            foreach ($week as $value) {
                if ($value['monday']['name'] != "") {
                    $weekList['monday'][] = ['section' => $value['section'], 'content' => $value['monday']];
                }

                if ($value['tuesday']['name'] != "") {
                    $weekList['tuesday'][] = ['section' => $value['section'], 'content' => $value['tuesday']];
                }

                if ($value['wednesday']['name'] != "") {
                    $weekList['wednesday'][] = ['section' => $value['section'], 'content' => $value['wednesday']];
                }

                if ($value['thursday']['name'] != "") {
                    $weekList['thursday'][] = ['section' => $value['section'], 'content' => $value['thursday']];
                }

                if ($value['friday']['name'] != "") {
                    $weekList['friday'][] = ['section' => $value['section'], 'content' => $value['friday']];
                }
                if ($value['saturday']['name'] != "") {
                    $weekList['saturday'][] = ['section' => $value['section'], 'content' => $value['saturday']];
                }
                if ($value['sunday']['name'] != "") {
                    $weekList['sunday'][] = ['section' => $value['section'], 'content' => $value['sunday']];
                }
            }
            if (!isset($weekList['monday'])) {
                $weekList['monday'] = [];
            }
            if (!isset($weekList['tuesday'])) {
                $weekList['tuesday'] = [];
            }
            if (!isset($weekList['wednesday'])) {
                $weekList['wednesday'] = [];
            }

            if (!isset($weekList['thursday'])) {
                $weekList['thursday'] = [];
            }
            if (!isset($weekList['friday'])) {
                $weekList['friday'] = [];
            }
            if (!isset($weekList['saturday'])) {
                $weekList['saturday'] = [];
            }
            if (!isset($weekList['sunday'])) {
                $weekList['sunday'] = [];
            }
            $list['curriculum'] = $weekList;
        }
        //判断软件下载是否存在
        $config['software'] = 1;
        if ($config['software'] == 1) {

        }

        //财经日历
        if ($config['whether_economics'] == 1) {
            $list['economics']['link'] = 'https://rili-d.jin10.com/open.php';
        }

        //市场评论
        if ($config['whether_market_review'] == 1) {
            $marketReview['list'] = MarketReview();
            array_unshift($marketReview['list'], ['title' => '全部', 'value' => 0]);

            $marketReviewList = $marketReview;

            $low_market_review = setRedis::getCache(session("website"), "marketLists");

            if ($low_market_review) {
                $market_review = $low_market_review;
            } else {
                $market_review = Market::select();
                if ($market_review) {
                    $market_review = $market_review->toArray();
                    setRedis::setCache(session("website"), "marketLists", $market_review, 0);
                }
            }
            foreach ($market_review as $value) {
                $value['release_time'] = date("Y-m-d H:i:s", $value['release_time']);
                $value['content'] = tohtml($value['content']);
                $marketReviewList['list'][0]['chilren'][] = $value;
                $marketReviewList['list'][$value['type']]['chilren'][] = $value;

            }
            $marketReviewList['cate'] = MarketReview();

            array_unshift($marketReviewList['cate'], ['title' => '全部', 'value' => 0]);
            $list['market_review'] = $marketReviewList;
        }

        //往期视频
        if ($config['whether_previous'] == 1) {
            $recordsList = Records::where("find_in_set({$data['roomid']},roomid)")->select()->each(function ($item) {
                $item['start_time'] = date("Y-m-d H:i:s", $item['start_time']);
                $item['stop_time'] = date("Y-m-d H:i:s", $item['stop_time']);
                $item['lecturer_name'] = Lecturer::where("id",$item['lecturer'])->value("name");
                $item['duration'] = handleTime($item['duration']);
                if ($item['mold'] == 'tencent') {
                    $item['appid'] = $item['domain'];
                }
            });
            if ($recordsList) $recordsList = $recordsList->toArray();
            // halt($recordsList);
            $recordsType = [
                0 => ['title' => '全部', 'value' => 0],
                1 => ['title' => '一周内', 'value' => 1],
                2 => ['title' => '一月内', 'value' => 2],
            ];
            $recordsParam = array();
            $recordsParam['cate'] = $recordsType;

            foreach ($recordsType as $value) {
                $value['chilren'] = array();
                $recordsParam['list'][] = $value;
            }
            $snowWeek = startStopTimes("sweek");   //本周的开始时间
            $enowWeek = startStopTimes('eweek');   //本周的结束时间

            $snowMonth = startStopTimes("smonth"); //本月的开始时间
            $enowMonth = startStopTimes("emonth"); //本月的结束时间
            foreach ($recordsList as $value) {
                $recordsParam['list'][0]['chilren'][] = $value;

                //当前时间戳
                $nowTime = strtotime($value['create_time']);


                if ($nowTime < $enowWeek || $nowTime > $snowWeek) {
                    $recordsParam['list'][1]['chilren'][] = $value;
                }

                if ($nowTime < $enowMonth || $nowTime > $snowMonth) {
                    $recordsParam['list'][2]['chilren'][] = $value;
                }

            }
            $list['previous'] = $recordsParam;
        }


        //高级课件
        if ($config['whether_advanced_courseware']) {


            $low_courseware = setRedis::getCache(session("website"), "courseWareLists");
            if ($low_courseware) {
                $courseware = $low_courseware;
            } else {
                $courseware = Courseware::select();
                if ($courseware) {
                    $courseware = $courseware->toArray();
                    setRedis::setCache(session("website"), "courseWareLists", $courseware, 0);
                }
            }

            if ($courseware) {
                foreach ($courseware as &$item) {
                    unset($item['create_time']);
                    unset($item['operation']);
                }
            }
            $list['courseware'] = $courseware;
        }

        return app("json")->success($list);
    }


    /**
     * 1分钟 -- 定时
     */
    public function timingOneMinute(Request $request)
    {
        //获取房间信息
        $data = Util::postMore([
            ['roomid', ''],
        ]);

        $list = array();

        session('website', $request->website());
        if ($data['roomid'] == '') return app("json")->fail("未选择房间号");
        //判断房间是否存在
        $low_roomInfo = setRedis::getCache(session("website"), "roomInfo" . $data['roomid']);
        if ($low_roomInfo) {
            $roomInfo = $low_roomInfo;
        } else {
            $roomInfo = Rooms::where("roomid", $data['roomid'])->find();
            if ($roomInfo) {
                $roomInfo = $roomInfo->toArray();
                setRedis::setCache(session("website"), "roomInfo" . $data['roomid'], $roomInfo);
            }
        }

        if ($roomInfo) {
            unset($roomInfo['id']);
            unset($roomInfo['create_time']);
            $list['info'] = $roomInfo;
        } else {
            return app("json")->fail("房间不存在");
        }


        //讲师投票列表
        $low_Lecturer = setRedis::getCache(session('website'), "LecturerList");
        if ($low_Lecturer) {
            $lecturer = $low_Lecturer;
        } else {
            $lecturer = Lecturer::where("state", 1)->order("rank desc")->select();
            if ($lecturer) {
                $lecturer = $lecturer->toArray();
                setRedis::setCache(session('website'), "LecturerList", $lecturer, 0);
            }

        }

        foreach ($lecturer as &$value) {
            $value['votes_total'] = (int)$value['votes'] + (int)$value['votes_dault'];
            unset($value['content']);
            unset($value['image']);
            unset($value['rooms']);
            unset($value['rank']);
            unset($value['create_time']);
            unset($value['website']);
            unset($value['state']);
            unset($value['votes']);
            unset($value['thumbs']);
            unset($value['votes_dault']);
            unset($value['thumbs_dault']);
            unset($value['id']);
        }

        $lecturerValue = array_column($lecturer, 'votes_total');
        array_multisort($lecturerValue, SORT_DESC, $lecturer);
        $list['lecturerList'] = $lecturer;
        return app("json")->success($list);
    }

    /**
     * 5分钟 --- 定时
     */
    public function timingFiveMinute(Request $request)
    {
        //获取房间信息
        $data = Util::postMore([
            ['roomid', ''],
        ]);
        session('website', $request->website());
        $list = array();

        $low_config = setRedis::getCache($data['website'], "info");

        if ($low_config) {
            $config = $low_config;
        } else {
            $config = SystemWebsite::where("website_ident", $data['website'])->find();
            if ($config) {
                $config = $config->toArray();
                setRedis::setCache($data['website'], 'info', $config, 0);
            }
        }
        if (isset($config['industry_dynamic_state'])) {
            if ($config['industry_dynamic_state'] == 1) {
                if(isset($config['industry_dynamic_content'])){
                    $quotationList = newsStockLists($config['industry_dynamic_content']);
                }else{
                    $quotationList = newsStockLists("");
                }
            }else{
                
                $low_quotationList = setRedis::getCache($data['website'], "digitalcurrency");
                
                if ($low_quotationList) {
                    $quotationList  = $low_quotationList;
                }else{
                    if(isset($config['industry_dynamic_content'])){
                    
                        $quotationList = currencyDigitalLists($config['industry_dynamic_content']);
                        if (empty($quotationList)) $quotationList = currencyDigitalLists($config['industry_dynamic_content']);
                    }else{
                        $quotationList = currencyDigitalLists("");
                        if (empty($quotationList)) $quotationList = currencyDigitalLists("");
                    }
                    
                    //储存到缓存里
                    setRedis::setCache($data['website'], 'digitalcurrency', $quotationList, 60*60);
                }
                

            }
        }else{
            $quotationList = newsStockLists("");
        }


       
        return app("json")->success(compact('quotationList'));

    }

    /**
     * 10分钟 --- 定时
     */
    public function timingTenMinute(Request $request)
    {
        $data = array();
    }

    /**
     * 行情动态
     */
    public function industry(Request $request)
    {
        $data['website'] = $request->website();
        session("website",$data['website']);
        $low_config = setRedis::getCache($data['website'], "info");
       
        if ($low_config) {
            $config = $low_config;
        } else {
            $config = SystemWebsite::where("website_ident", $data['website'])->find();
            if ($config) {
                $config = $config->toArray();
                setRedis::setCache($data['website'], 'info', $config, 0);
            }
        }
        if (isset($config['industry_dynamic_state'])) {
            if ($config['industry_dynamic_state'] == 1) {
                if(isset($config['industry_dynamic_content'])){
                    $list = newsStockLists($config['industry_dynamic_content']);
                }else{
                    $list = newsStockLists("");
                }
            }else{
                
                $low_list = setRedis::getCache($data['website'], "digitalcurrency");
                
                if ($low_list) {
                    $list  = $low_list;
                }else{
                    if(isset($config['industry_dynamic_content'])){
                    
                        $list = currencyDigitalLists($config['industry_dynamic_content']);
                        if (empty($list)) $list = currencyDigitalLists($config['industry_dynamic_content']);
                    }else{
                        $list = currencyDigitalLists("");
                        if (empty($list)) $list = currencyDigitalLists("");
                    }
                    
                    //储存到缓存里
                    setRedis::setCache($data['website'], 'digitalcurrency', $list, 60*60);
                }
                

            }
        }else{
            $list = newsStockLists("");
        }
        return app("json")->success($list);
    }

    /**
     * 仓库管理
     */
    public function warehouse(Request $request)
    {
        //获取房间信息
        $data = Util::postMore([
            ['type', 'open']
        ]);
        if ($data['type'] == '') return app("json")->fail("参数类型错误");
        session('website', $request->website());
        $list = array();
        switch ($data['type']) {
            case 'open':
                $low_list = setRedis::getCache(session("website"), "openGranaryProvideList");
                if ($low_list) {
                    $list = $low_list;
                } else {
                    $list = Warehouse::where("close_time", 0)->select();
                    if ($list) {
                        $list = $list->toArray();
                        setRedis::setCache(session("website"), "openGranaryProvideList", $list, 0);
                    }
                }
                break;
            case 'close':
                $low_list = setRedis::getCache(session("website"), "closeGranaryProvideList");
                if ($low_list) {
                    $list = $low_list;
                } else {
                    $list = Warehouse::where("close_time", "<>", 0)->select();
                    if ($list) {
                        $list = $list->toArray();
                        setRedis::setCache(session("website"), "closeGranaryProvideList", $list, 0);
                    }
                }
                break;
        }
        if ($list) {
            foreach ($list as &$item) {
                $item['open_time'] = date("Y-m-d H:i:s", $item['open_time']);
                $item['close_time'] = date("Y-m-d H:i:s", $item['close_time']);
                $item['type_name'] = stocksTypeName($item['type']);
                unset($item['create_time']);
            }
        }

        return app("json")->success($list);
    }


    /**
     * 腾讯云 视频回调
     */
    public function TencentVideoCallback ()
    {
        $data = Util::getMore([
            ['appid', ''],
            ['stream_id', ''],
            ['channel_id', ''],
            ['file_id', ''],
            ['file_format', ''],
            ['start_time', ''],
            ['end_time', ''],
            ['duration', ''],
            ['file_size', ''],
            ['stream_param', ''],
            ['video_url', ''],
            ['website', '']
        ]);

        $data['website'] = $_GET['website'];

        if ($data) {
            if ($data['appid'] == '' || $data['stream_id'] == '' || $data['channel_id'] == '' || $data['file_id'] == '' || $data['file_format'] == '' || $data['start_time'] == '' || $data['end_time'] == '' || $data['duration'] == '' || $data['file_size'] == '' || $data['stream_param'] == '' || $data['video_url'] == '') {
                $json = file_get_contents("php://input");
                $data = json_decode($json, true);
                $data['website'] = $_GET['website'];
            }
        }

        if ($data['appid'] == '' || $data['stream_id'] == '' || $data['channel_id'] == '' || $data['file_id'] == '' || $data['file_format'] == '' || $data['start_time'] == '' || $data['end_time'] == '' || $data['duration'] == '' || $data['file_size'] == '' || $data['stream_param'] == '' || $data['video_url'] == '') {
            $videoError = new VideoCallError([], $data['website']);
            $videoError->save(['type' => 'tencent', 'create_time' => time()]);
            return app("json")->success("回调失败");
        }
        if ($data['website'] == '') return app("json")->fail("网站标识不存在");
        session("website", $data['website']);
        $info = array();
        $info['domain'] = $data['appid'];
        $info['app'] = $data['stream_id'];
        $info['stream'] = $data['channel_id'];
        $info['file_id'] = $data['file_id'];
        $info['type'] = $data['file_format'];
        $info['start_time'] = $data['start_time'];
        $info['stop_time'] = $data['end_time'];
        $info['duration'] = $data['duration'];
        $info['size'] = $data['file_size'];
        $info['mold'] = 'tencent';
        $info['params'] = $data['stream_param'];
        $info['uri'] = $data['video_url'];

        $save = Records::save($info);
        return $save ? app("json")->success("添加成功") : app("json")->fail("添加失败");
    }

    /**
     * 又拍云视频回调
     */
    public function upyunVideoCallback ()
    {
        $data = Util::postMore([
            ['domain', ''],
            ['app', ''],
            ['stream', ''],
            ['uri', ''],
            ['duration', ''],
            ['start_time', ''],
            ['stop_time', ''],
            ['website', '']
        ]);

        if ($data['domain'] == '' || $data['app'] == '' || $data['stream'] == '' || $data['uri'] == '' || $data['duration'] == '' || $data['start_time'] == '' || $data['stop_time'] == '' || $data['website'] == '') {
            $json = file_get_contents("php://input");
            $data = json_decode($json, true);
            $data['website'] = $_GET['website'];
        }

        if ($data['domain'] == '' || $data['app'] == '' || $data['stream'] == '' || $data['uri'] == '' || $data['duration'] == '' || $data['start_time'] == '' || $data['stop_time'] == '' || $data['website'] == '') {
            $videoError = new VideoCallError([], $data['website']);
            $videoError->save(['type' => 'tencent', 'create_time' => time()]);
            return app("json")->success("回调失败");
        }

        session("website", $data['website']);
        $info = array();
        $info['domain'] = $data['domain'];
        $info['app'] = $data['app'];
        $info['stream'] = $data['stream'];
        $info['uri'] = $data['uri'];
        $info['duration'] = $data['duration'];
        $info['start_time'] = $data['start_time'];
        $info['stop_time'] = $data['stop_time'];

        $save = Records::save($info);
        return $save ? app("json")->success("添加成功") : app("json")->fail("添加失败");
    }

    /**
     * 测试
     */
    public function test()
    { 
        // asd
    }


    /**
     * 修改房间信息
     */
    public function editRooms(Request $request)
    {
        $data = Util::postMore([
            ['roomid', ''],
            ['message_audit', ''],
        ]);

        session('website', $request->website());
        if ($data['roomid'] == '' || $data['message_audit'] == '') return app("json")->fail("参数错误");
        $roomid = $data['roomid'];
        unset($data['roomid']);

        Rooms::where("roomid", $roomid)->update($data);

        $roomInfo = Rooms::where("roomid", $roomid)->find();
        $roomInfo = $roomInfo->toArray();
        setRedis::setCache(session("website"), "roomInfo" . $roomid, $roomInfo);

        return app("json")->success('修改成功');


    }

    //上传文件
    public function uploadfile(Request $request)
    {
        // 允许跨域
        header('Access-Control-Allow-Origin:*');

        $data = [
            'upload_type' => 'alioss',
            'file' => $this->request->file('file'),
        ];
        
        if (empty($data['file'])) app("json")->fail("文件不存在");
        $uploadConfig = sysconfig('upload');
        empty($data['upload_type']) && $data['upload_type'] = $uploadConfig['upload_type'];
        $rule = [
            'upload_type|指定上传类型有误' => "in:{$uploadConfig['upload_allow_type']}",
            'file|文件' => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}",
        ];

        $this->validates($data, $rule);
        session("receptionurl", "receptionurl");
        try {
            $upload = Uploadfile::instance()
                ->setUploadType($data['upload_type'])
                ->setUploadConfig($uploadConfig)
                ->setFile($data['file'])
                ->save();
        } catch (\Exception $e) {
            return app("json")->fail($e->getMessage());
        }

        if ($upload['save'] == true) {
            return app("json")->success(['url' => $upload['url']]);
        } else {
            return app("json")->fail($upload['msg']);
        }
    }


    //高级课件下载次数

    public function CoursewareDowold (Request $request) 
    {
        $data = Util::postMore([
            ['id', ''],
        ]);
        session('website', $request->website());
        Courseware::where("id",$data['id'])->inc("number", 1)->save();
        return app("json")->success("下载成功");

    }

}